package tech.yunland.shop.domain.service;

import com.moyuer.bsf.domain.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.yunland.shop.domain.dao.UserActivityDao;
import tech.yunland.shop.domain.model.UserActivity;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户活跃度服务类
 *
 * @author 文卡<wkwenka@gmail.com>  on 17-5-24.
 */
@Service
public class UserActivityService {

    @Autowired
    private UserActivityDao userActicityDao;

    @Autowired
    private UserService userService;

    /**
     * 增加/保存用户活跃度积分
     *
     * @param userId
     * @param activeScore
     */
    public void saveOrUpdate(String userId, BigInteger activeScore) {

        //查询用户活跃度表中该用户是否存在
        String hql = "FROM UserActivity WHERE user.id = ?";
        List<UserActivity> userActivities = userActicityDao.find(hql, userId);

        if (userActivities != null && userActivities.size() > 0) {
            //修改活跃度积分
            if (userActivities.size() == 1) {
                UserActivity userActivity = userActivities.get(0);
                userActivity.setActiveScore(userActivity.getActiveScore().add(activeScore)); // 增加相对应用户的活跃度积分
                userActivity.setUpdateTime(new Date());
                userActicityDao.update(userActivity);
            } else {
                throw new RuntimeException("用户活跃度数据异常");
            }
        } else {
            //保存
            UserActivity userActivity = new UserActivity();
            userActivity.setUpdateTime(new Date());
            userActivity.setUser(userService.get(userId));
            userActivity.setActiveScore(activeScore);
            userActicityDao.save(userActivity);
        }

    }

    /**
     * 获取用户积分
     *
     * @param userId
     * @return
     */
    public String getActiveScore(String userId) {
        String sql = "select active_score from user_activity where user_id = ?";
        List<Map<String, Object>> bySQL = this.userActicityDao.findBySQL(sql, userId);
        if (bySQL != null && bySQL.size() > 0) {
            if (bySQL.size() == 1) {
                return ((BigInteger) bySQL.get(0).get("active_score")).toString();
            } else {
                throw new RuntimeException("数据异常");
            }
        } else {
            return "0";
        }
    }
}
